import configs from '../config'
// 返回操作
function back(delta = 1) {
  wx.navigateBack({
    delta,
    fail: function () {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  })
}

// 节流
function throttle(fn, duration) {
  if (duration == null || duration == undefined) {
    duration = 1500
  }
  let _lastTime = null
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > duration || !_lastTime) {
      fn.apply(this, arguments)
      _lastTime = _nowTime
    }
  }
}
// 防抖
function debounce(fn, duration) {
  let timer
  const gapTime = duration || 1000;
  return function () {
    clearTimeout(timer)
    const context = this
    const args = arguments
    timer = setTimeout(function () {
      fn.call(context, args)
    }, gapTime)
  };
}

// 退出账号逻辑
function logoutSuccess() {
  // 保存当前年级
  wx.setStorageSync('tmp_grade', wx.getStorageSync('userInfo').grade)
  // 清除缓存
  wx.removeStorageSync('token')
  wx.removeStorageSync('account')
  wx.removeStorageSync('userInfo')
  wx.removeStorageSync('view_record')
  wx.removeStorageSync('close_add_tips')
  wx.removeStorageSync('appToken')
  wx.removeStorageSync('appInfo')
  // 停止后台音频
  wx.getBackgroundAudioManager().stop()
}


// 跳转逻辑
function nav(path) {
  if (!path) {
    console.log(`配置的跳转链接有误,path:${path}`)
    return
  }
  wx.navigateTo({
    url: path,
    fail() {
      // tab页面
      // path要和params分离
      const tmp = path.split('?')
      const url = tmp[0]
      let params = {}
      if (tmp.length > 1) {
        const paramStr = tmp[1].split('&')
        for (let i = 0; i < paramStr.length; i++) {
          const v = paramStr[i].split('=')
          params[v[0]] = v[1]
        }
      }
      if (params) {
        wx.setStorageSync('switch_tab_params', params)
      }
      wx.switchTab({
        url: url,
        fail() {
          // 非法链接
          wx.showToast({
            title: '链接有误',
            icon: 'none'
          })
          console.error(`配置的跳转链接有误,path:${path}`)
        }
      })
    }
  })
}

// 左侧补零
function addZero(val) {
  if (val < 10) {
    return 0 + '' + val
  } else {
    return val
  }
}

// 时间格式化
// fill  完整
function formatSeconds(value, format = null, fill = false) {
  var secondTime = parseInt(value); // 秒
  var minuteTime = 0; // 分
  var hourTime = 0; // 小时
  if (secondTime > 60) {
    minuteTime = parseInt(secondTime / 60);
    secondTime = parseInt(secondTime % 60);
    if (minuteTime > 60) {
      hourTime = parseInt(minuteTime / 60);
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  var result = addZero(parseInt(secondTime)) + (format ? '秒' : '');
  if (minuteTime > 0) {
    result = addZero(parseInt(minuteTime)) + (format ? '分' : ':') + result;
  } else {
    result = (!format ? addZero(parseInt(minuteTime)) + ":" : '') + result
  }
  if (hourTime > 0 || fill) {
    result = addZero(parseInt(hourTime)) + (format ? '时' : ':') + result;
  }
  return result;
}

// 格式化文件大小
function formatFileSize(fileLength) {
  return (fileLength / 1024 / 1024).toFixed(2)
}

// 格式化富文本内容
function formatRichText(html) {
  if (!html) {
    return html
  }
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}

// 隐藏姓名
function hideName(name) {
  const arr = name.split('')
  if (arr.length == 0) return ''
  if (arr.length == 2) {
    return arr[0] + '*'
  }
  return arr[0] + '*' + arr[arr.length - 1]
}

function checkApi(apiStr) {
  if (wx.canIUse(apiStr)) {
    return true
  } else {
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
    })
  }
}

// 现在输入长度
function limitstr(strval, strnum) {
  let re = "";
  let strleng = strval.length;
  //返回字符串的总字节数
  let byteleng = strval.replace(/[^\x00-\xff]/g, '**').length;
  if (byteleng <= strnum) return strval;
  for (var i = 0, bytenum = 0; i < strleng; i++) {
    var byte = strval.charAt(i);
    if (/[\x00-\xff]/.test(byte)) {
      bytenum++; //单字节字符累加1
    } else {
      bytenum += 2; //非单字节字符累加2
    }
    if (bytenum <= strnum) {
      re += byte
    } else {
      return re
    }
  }
}


// 获取当前页面的路由
function getCurRoute() {
  const pages = getCurrentPages()
  const curPage = pages[pages.length - 1]
  const route = buildRoute(curPage)
  return route
}


// 构造当前页面路径
function buildRoute(page) {
  const route = '/' + page.route
  if (!page.options) {
    return route
  }
  const ops = []
  for (let k in page.options) {
    ops.push(`${k}=${page.options[k]}`)
  }
  // 加入邀请用户id
  const userInfo = wx.getStorageSync('userInfo')
  if (userInfo) {
    ops.push(`shareId=${userInfo.id}`)
  }
  return `${route}?${ops.join('&')}`
}


const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 获取配置
function getConfig(key = '') {
  if (key === '') {
    return configs
  }
  if (!configs[key]) {
    console.log('config is not exist')
    return ''
  }
  // 是否区分环境
  if (typeof configs[key] === 'object') {
    const localEnv = getConfig('env')
    let {
      miniProgram: {
        envVersion
      }
    } = wx.getAccountInfoSync()
    // 优先判断本地环境是否为线上版本
    if (localEnv == 'release' || localEnv == 'prepro') {
      envVersion = localEnv
    }
    return configs[key][envVersion]
  }
  return configs[key]
}


module.exports = {
  formatTime,
  back,
  throttle,
  debounce,
  logoutSuccess,
  nav,
  formatSeconds,
  formatFileSize,
  formatRichText,
  hideName,
  checkApi,
  limitstr,
  getCurRoute,
  getConfig
}